package vue;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.finalprojet.R;

public class UploadImage extends Activity {

String pseudo;
protected Uri image=null;
public String nomimg = null;
File fichier; 
int check = 0;
String ident = null;
private ProgressBar dialog;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_image);
        
        //pseudo = getIntent().getStringExtra("pseudo");
        dialog = (ProgressBar)findViewById(R.id.progressBar1);
        if ( getIntent().getStringExtra("id") != null) ident = getIntent().getStringExtra("id");


    	if ( getIntent().getStringExtra("fichier") != null) 
    		
    		fichier = new File(getIntent().getStringExtra("fichier"));
    	Intent intent = new Intent();
    	intent.setType("image/*");
    	intent.setAction(Intent.ACTION_GET_CONTENT);
    	startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
        
        
    }


    

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onStop() {
Log.i(getClass().getSimpleName(),"on stop");
super.onStop();
}

@Override
protected void onDestroy() {
super.onDestroy();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { 

        if (resultCode == RESULT_OK) {

                if (requestCode == 1) {

                        // currImageURI is the global variable I'm using to hold the content:// URI of the image
                	///image = data.getData();
                	//nomimg = getRealPathFromURI(image);
                	//Toast.makeText(getApplicationContext(),  data.getData().toString()   , Toast.LENGTH_LONG).show(); 
                	
                	if ( data.getData().toString().startsWith("content://media/external/"))
                	fichier = new File(getRealPathFromURI(data.getData()));
                	
                	else fichier = new File( data.getData().toString().substring(6));
                	
                	
                	httpTask req = new httpTask();
            		req.execute(fichier);
                	
                	
                }
        }
}

// And to convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        @SuppressWarnings("deprecation")
		Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}



public class httpTask extends AsyncTask< File, Integer, String>   
{



	 protected String doInBackground(File... arg0) {
		 
		 
		
		Uri image = null;
		 image = Uri.fromFile(arg0[0]);

		 String lineEnd = "\r\n";
		 String twoHyphens = "--";
		 String boundary = "*****";
		 String photofile = null;
		 String httpResponse; 
		 //String ext = image.toString().substring(image.toString().length()-4);
		 String filename= ident;
		// filename += ext;
		 filename += ".jpg";
		// String urlString = "http://192.168.0.14/fileUpload.php";
		 
		 String urlString = "https://spartacus.iutc3.unicaen.fr/~projet.echec/android/fileUpload.php";
		 
		 
		 HttpURLConnection conn = null;
		 

		 InputStream fis = null;
		 Bitmap mBitmap=null;
		 //String pathfile;

		 try {
		 fis = getContentResolver().openInputStream(image);
		 mBitmap = BitmapFactory.decodeStream(fis);

		 try {
		 @SuppressWarnings("unused")
		int bytesAvailable = fis.available();
		 } catch (IOException e) {
			 e.printStackTrace();
		 Log.i(getClass().getSimpleName(),"échec de lecture de la photo");
		 }
		 } catch (FileNotFoundException e) {
		 e.printStackTrace();
		 Toast.makeText(UploadImage.this, "échec de lecture de la photo ", Toast.LENGTH_SHORT).show();
		 Log.i(getClass().getSimpleName(),"échec de lecture de la photo");
		 }
		 
		

		 try {
		 URL site = new URL(urlString);
		 //conn.

		 conn = (HttpURLConnection) site.openConnection();

		 //on peut �crire et lire
		 conn.setDoOutput(true);
		 conn.setDoInput(true);

		 // Use a post method.
		 conn.setRequestMethod("POST");
		 conn.setRequestProperty("Connection", "Keep-Alive");
		 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
		 
		 
		 String userpassword = "projet.echec" + ":" + "eepuhohx";
	      String encodedAuthorization =  Base64.encodeToString( userpassword.getBytes(), Base64.NO_WRAP );
	      conn.setRequestProperty("Authorization", "Basic "+
	            encodedAuthorization);
		
	      
		 DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

		 dos.writeBytes(twoHyphens + boundary + lineEnd);
		 Log.i(getClass().getSimpleName(),"Display name : " + photofile);
		 Log.i(getClass().getSimpleName(),"Filename : " + filename);
		 dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename + "\"" + lineEnd);
		 dos.writeBytes(lineEnd);

		 Log.i(getClass().getSimpleName(),"Headers are written");

		 //compression de image pour envoi
		 mBitmap.compress(CompressFormat.JPEG, 75, dos);

		 
		 
		 
		 
	//	 byte[] buffer;
		 
		 // send multipart form data necesssary after file data...
		 dos.writeBytes(lineEnd);
		 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
		 
		 // close streams
		 fis.close();
		 dos.flush();
		 dos.close();
		 Log.e("fileUpload","File is written on the queue");

		 } catch (MalformedURLException e) {
		 e.printStackTrace();
		 Toast.makeText(UploadImage.this, "échec de connexion au site web ", Toast.LENGTH_SHORT).show();
		 Log.i(getClass().getSimpleName(),"échec de connexion au site web 1");
		 } catch (IOException e) {
		 e.printStackTrace();
		 Toast.makeText(UploadImage.this, "échec de connexion au site web ", Toast.LENGTH_SHORT).show();
		 Log.i(getClass().getSimpleName(),"échec de connexion au site web 2");
		 }
		 
		 
		 try {
			 BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			 Log.i(getClass().getSimpleName(),"try HTTP reponse");
			 while ((httpResponse = rd.readLine()) != null) {
			 Log.i(getClass().getSimpleName(),"HTTP reponse= " + httpResponse);
			 if(httpResponse.contains("error")) {
			 //there is a http error
			 check = 1;
			 }
			 }
			 rd.close();
			 } catch (IOException ioex){
			 Log.e("HttpUploader", "error: " + ioex.getMessage(), ioex);
			 ioex.printStackTrace();
			 Toast.makeText(UploadImage.this, "échec de lecture de la réponse du site web ", Toast.LENGTH_SHORT).show();
			 Log.i(getClass().getSimpleName(),"échec de lecture de la réponse du site web");
			 }

	 
	 
	 return null;
	 
	 
	 }
	 
	 
	 @Override
	 protected void onProgressUpdate(Integer...values)
	 {
		 
		 for (int i=0; i<100; i++)
		 {
			
		 dialog.setProgress(i);
		 
		 }
	 }
			 
		  
		 
		 

		 
		 
		 
		 
		

		protected void onPostExecute(String result) 
		{
		//Intent nextScreen = new Intent(getApplicationContext(),Reglage.class);
		//nextScreen.putExtra("pseudo",pseudo);
		//startActivity (nextScreen);
		finish();
		}
			

}
























    }

